﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ModbusTest
{
    public class LogSaver
    {
        public static string LogFolder
        {
            get
            {
                return "D:\\Data";
            }
        }
        public static void AddHeader(string ModuleName,string StationName, string Header)
        {
            string strDate = DateTime.Now.ToString("yyyy-MM-dd");
            string filePath = string.Format("{0}\\{1}\\{2}", LogFolder,ModuleName, StationName);
            if (Directory.Exists(filePath) == false)
            {
                Directory.CreateDirectory(filePath);
            }
            string fileAbstractPath = string.Format("{0}\\{1}_{2}_{3}.csv", filePath, ModuleName, StationName, strDate);
            if (!File.Exists(fileAbstractPath))
            {
                FileStream fsHeader = new FileStream(fileAbstractPath, FileMode.OpenOrCreate);
                using (StreamWriter swH = new StreamWriter(fsHeader))
                {
                    swH.WriteLine("日期,时间," + Header);
                    swH.Close();
                }
            }
        }
        public static void AddLog(string ModuleName, string StationName, string msg)
        {
            string tishiMsg = "";
            try
            {
                string strDate = DateTime.Now.ToString("yyyy-MM-dd");
                string filePath = string.Format("{0}\\{1}\\{2}", LogFolder, ModuleName, StationName);
                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);
                }
                string fileAbstractPath = string.Format("{0}\\{1}_{2}_{3}.csv", filePath, ModuleName, StationName, strDate);
                FileStream fs = new FileStream(fileAbstractPath, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入     
                string time = DateTime.Now.ToString("yyyy-MM-dd,HH:mm:ss");
                msg = time + "," + msg + System.Environment.NewLine;

                sw.Write(msg);
                //清空缓冲区               
                sw.Flush();
                //关闭流               
                sw.Close();
                sw.Dispose();
                fs.Close();
                fs.Dispose();

                tishiMsg = "写入日志成功";
            }
            catch (Exception ex)
            {
                string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                tishiMsg = "[" + datetime + "]写入日志出错：" + ex.Message;
            }
        }
        /// <summary>
        /// 系统时间
        /// </summary>
        /// <returns></returns>
        public static string time()
        {
            string dNow = DateTime.Now.ToString().Trim().Replace("/", "").Replace(":", "");
            string fileName = dNow.ToString();
            return fileName;
        }

    }
}
